<?php

namespace app\mfw_order\controller;

use think\Db;

require_once EXTEND_PATH.'newMfw-sdk/Openapi.php';

/**
 *  马蜂窝订单标记颜色
 * Class MfwOrderMark
 * @package app\mfw_order\controller
 */
class MfwOrderMark
{

    public $count = 1;
    /**
     * 构造函数
     * MfwComment constructor.
     */
    public function __construct(){}

    /**
     *  子进程启动时触发
     * @param $worker
     */
    public function onWorkerStart($worker){
        echo "马蜂窝订单标记颜色子进程启动了\n";
        sleep(10);
        \workerman\Lib\Timer::add(30,[$this, 'timeTask']); // 定时器
    }

    /**
     * 连接时触发
     * @param $connection
     */
    public function onConnect($connection){
        echo "连接成功\n";
        $connection->send('<h2 style="color: #4288ce;font-size: 20px">hello!</h2>');
    }

    /**
     *  接收到消息时触发
     * @param $connection
     * @param $message
     */
    public function onMessage($connection, $message) {
        var_dump($message);
        $connection->send("<span style='color: #000088;'>很高兴和你认识</span>\n");
    }

    /**
     *  连接关闭时触发
     * @param $connection
     */
    public function onClose($connection){
        echo "连接断开了\n";
    }

    /**
     *  worker进程停止时触发
     * @param $connection
     */
    public function onWorkerStop($connection){
        echo "正在重启!\n";
    }


    /*8
    *
     *  定时任务
     */
    public function timeTask()
    {
//        logs('mfw_order_count', $this->count++);
        $orderIds  = self::getOrderId();
//        logs('orderIds', $orderIds);
        if (!empty($orderIds) && strlen($orderIds['order_id']) > 5){
            $this->getMfwOrderMark($orderIds['order_id'], $orderIds['val']);
        }
    }

    /**
     *  获取马蜂窝订单标记颜色
     * @author 邓汉炜
     * @url /mfw_order/mfw_order_mark/getMfwOrderMark
     */
    public function getMfwOrderMark($orderId = '',$val = 1)
    {
        $action = 'sales.order.color.get'; // 调用接口的动作
        $data = [];
        $data['order_id'] = empty($orderId) ? '':$orderId;
        // 实例化对象
        $mfwObj = new \MSDK_Php_Openapi();
        // 请求接口
        if (false == $mfwObj->send($action, $data)){
            $msg['msg'] = '接口调用失败';
            $msg['error'] = $mfwObj->getError();
            $msg['order'] = $orderId;
            $msg['errno'] = $mfwObj->getErrno();
            logs('mfw_order_mark_error', date('Y-m-d H:i:s', time()));
            logs('mfw_order_mark_error', $msg);
        } else {
            $getData = $mfwObj->getData();
            // 查找订单的颜色和次数
            $orderData = Db::name('order')->where('order_id',$orderId)->find();
            if ($orderData['frequency'] == 14){
                Db::name('order')->where('order_id',$orderId)->update(['frequency'=>16]);
            }else{
                Db::name('order')->where('order_id',$orderId)->setInc('frequency'); // 自增加一
            }
            if ($val == 2){
                Db::name('order')->where('order_id',$orderId)->update(['frequency'=>15]);
            }
            // 更改订单的颜色
            if ($getData['color'] != $orderData['color']){
                Db::name('order')->where('order_id',$orderId)->update(['color'=>$getData['color']]);
            }
        }
    }

    /**
     *  获取订单id
     */
    public static function getOrderId()
    {
        // 从订单表获取马蜂窝订单id,如果没有h开头的就是从马蜂窝同步的订单;获取到的订单时h的，frequency更新为15,当该字段值为15时不再更新
        // 获取的是没有更新颜色的订单
        $order = Db::name('order')
            ->where('frequency','<>',15)
            ->where('color',10)
            ->where('platform','mfw')
            ->order('frequency','asc')
            ->find();

//        logs('dsdfds',$order);
        if (empty($order)){ // 订单为空
            $order = Db::name('order')
                ->where('frequency','<>',15)
                ->where('color','<>',10)
                ->where('platform','mfw')
                ->order('frequency','asc')
                ->find();
        }

        $orderIds = [];
        if (!empty($order)){
            // 如果是后台手动添加的订单，将frequency更新为15
            if (substr($order['order_id'], 0,1) == 'h' || !is_numeric($order['order_id']) || strlen($order['order_id']) < 5){
                Db::name('order')->where('order_id',$order['order_id'])
                    ->where('platform','mfw')->update(['frequency'=>15]);
                return $orderIds;
            }
            if (empty($order['is_review'])){ // 无点评
                $orderIds = [
                    'order_id' => $order['order_id'],
                    'val' => 1
                ];
            }elseif ($order['order_status'] == 'close'){ // 有点评,订单已关闭,最后一次更新订单标记颜色
                $orderIds = [
                    'order_id' => $order['order_id'],
                    'val' => 2
                ];
            }elseif ($order['is_review']){
                $orderIds = [
                    'order_id' => $order['order_id'],
                    'val' => 1
                ];
            }
            if ($order['frequency'] >= 4294967280){
                Db::name('order')->where('order_id',$order['order_id'])->where('platform','mfw')->update(['frequency'=>4294967118]);
            }
            return $orderIds;
        } else {
            return $orderIds;
        }
    }

}
